import Axios from 'axios'
import app from '../main'

// 建立请求
const request = (method, url, data, options, file) => {
  app.$spin.show()
  // 如果是GET请求，则处理参数
  options = method === 'get' ? { params: options } : options
  let config = Object.assign({}, { 
    // 默认配置
    method,
    url,
    data,
    timeout: file ? 30000 : 10000
  }, options)
  // 如果是POST请求，添加headers
  if (method === 'post') {
    config.headers = Object.assign({ 'Content-Type': 'application/json; charset=UTF-8' }, config.headers)
  }
  // 发起请求
  return Axios(url, config).then(result => {
    app.$spin.hide()
    const code = result.data.code
    if (code == 200) {
      return result.data
    } else if (code == '315') {
      app.$toast('登录信息失效，请重新登录...', () => {
        app.$router.push('/login')
      })
    } else if (code == '360' || code == '380' || code == '381' || code == '332') {
      app.$toast(result.data.msg)
      return result.data
    } else if (code == '310' || code == '311' || code == '329' || code == '401') {
      // 310 用户已存在, 311 用户不存在，401：运费模板不存在
      return result.data
    } else {
      app.$toast(result.data.msg)
    }
  }).catch(err => {
    app.$toast('请求超时，请稍后再试')
  })
}

// 导出
export default {
  get(url, config) {
    return request('get', url, null, config)
  },
  post(url, data, config) {
    return request('post', url, data, config)
  },
  post2(url, data, config, file) {
    return request('post', url, data, config, 'file')
  }
}